package com.hq.shop12auth.controller;

import com.hq.commons.common.R;
import com.hq.commons.constatns.AuthConstatns;
import com.hq.commons.constatns.CarConstatns;
import com.hq.commons.constatns.RabbitMQConstatns;
import com.hq.commons.constatns.RedisConstatns;
import com.hq.commons.ov.Customer;
import com.hq.commons.ov.Sms;
import com.hq.commons.utils.PassWordUtils;
import com.hq.shop12auth.feign.api.CarService;
import com.hq.shop12auth.feign.api.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Autowired
    private UserService service;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CarService carService;

    @PostMapping("checkUsername")
    @ResponseBody
    public Map<String, Object> checkUsername(String param) {
        Map<String, Object> map = new HashMap<>();
//        检查用户名是否存在
        Customer userByName = service.getUserByName(param);

        if (userByName == null) {
            map.put("status", "y");
            map.put("info", "可以注册");
        } else {
            map.put("status", "n");
            map.put("info", "用户名已被注册，请更换其他的用户名");
        }
        return map;
    }

    @GetMapping("sendSms/{phone}")
    @ResponseBody
    public void sendSms(@PathVariable String phone) {
//        生成一个验证码
        String code = RandomStringUtils.random(6, false, true);
//        把生成的验证码放到Redis中
        redisTemplate.opsForValue().set(RedisConstatns.AUTH_REGISTER_CODE + phone, code, 60, TimeUnit.SECONDS);
//        发送短信
        Sms sms = new Sms();
        sms.setPhone(phone);
        sms.setCode(code);
        rabbitTemplate.convertAndSend(RabbitMQConstatns.SEND_MESSAGE_EXCHANGE, "send.sms.phone", sms);
        System.out.println("短信发送完成，code是：" + code);
    }

    @PostMapping("registerUser")
    @ResponseBody
    public R registerUser(Customer customer) {
//        后台做验证
        String code = customer.getCode();
        String phone = customer.getPhone();
//        查询用户在Redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(RedisConstatns.AUTH_REGISTER_CODE + phone);
        if (StringUtils.isEmpty(redisCode) || !code.equals(redisCode)) {
            return R.error("验证码已过期，请重新获取");
        }
        if (!redisCode.equals(code)) {
            return R.error("验证码不正确，请重新输入");
        }
//        密码加密
        customer.setPassword(PassWordUtils.hashPws(customer.getPassword()));
        Boolean aBoolean = service.addUser(customer);
        return R.success(aBoolean);
    }

    //    @CookieValue(name = CarConstatns.ANNE_CAR_COOK_NAME) String anneId
    @PostMapping("login")
    @ResponseBody
    public R login(String username, String password, HttpServletRequest request
            , @CookieValue(name = CarConstatns.ANNE_CAR_COOK_NAME, defaultValue = "") String anneId) {
//        判断用户名是否存在
        Customer customer = service.getUserByName(username);
//        非空判定，密码对比
        if (customer == null || !PassWordUtils.checkPw(password, customer.getPassword())) {
            return R.error("用户名或密码错误");
        }
//       认证成功
        request.getSession().setAttribute(AuthConstatns.AUTH_SESSION, customer);
//        合并购物车
        if (!StringUtils.isEmpty(anneId)) {
            carService.mergeCar(customer.getId(), anneId);
        }
//        返回成功
        return R.success();
    }

    @GetMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "redirect:http://localhost:81/auth/login.html";
    }
}
